package javaweb;

import org.junit.Test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDP {
    @Test
    public void sender(){
        try {
            //1.实例化发送端DatagramSocket()
            InetAddress localHost = InetAddress.getLocalHost();
            DatagramSocket socket = new DatagramSocket();
            byte[] bytes="学海无涯，回头是岸".getBytes();
            //2.打包数据(参数:数据长度,发送地址,端口)
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, localHost, 8088);
            //3.发送
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void receiver(){
        try {
            DatagramSocket socket = new DatagramSocket(8088);
            byte[] bytes=new byte[100];
            DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
            socket.receive(packet);
            System.out.println(new String(packet.getData(),0,packet.getLength()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
